package ui.fragment;

import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityOptionsCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fy.fyzf.R;
import com.fy.fyzf.api.ApiConstant;
import com.fy.fyzf.api.ApiRetrofit;
import com.fy.fyzf.base.BaseFragment;
import com.fy.fyzf.base.Contans;
import com.fy.fyzf.bean.AreaListBean;
import com.fy.fyzf.bean.BaseData;
import com.fy.fyzf.bean.CategoryBean;
import com.fy.fyzf.bean.FiltrateBean;
import com.fy.fyzf.bean.HomeBannerBean;
import com.fy.fyzf.bean.HousesBean;
import com.fy.fyzf.bean.HousesListBean;
import com.fy.fyzf.bean.HousingCountBean;
import com.fy.fyzf.bean.NearBean;
import com.fy.fyzf.bean.NearHousingBean;
import com.fy.fyzf.bean.PriceFilterBean;
import com.fy.fyzf.dialog.AreaFilterPopwindow;
import com.fy.fyzf.dialog.CityDetailFilterPopwindow;
import com.fy.fyzf.dialog.FlowPopWindow;
import com.fy.fyzf.dialog.PriceFilterPopwindow;
import com.fy.fyzf.glideUtils.GlideUtils;
import com.fy.fyzf.presenter.HouseSoucePresenter;
import com.fy.fyzf.utils.AppUtils;
import com.fy.fyzf.utils.GetJsonDataUtil;
import com.fy.fyzf.utils.ShareHelper;
import com.fy.fyzf.view.HouseSouceView;
import com.fy.fyzf.view.SpacesItemDecoration;
import com.fy.fyzf.wifi.WifiConfig;
import com.google.android.material.appbar.AppBarLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.stx.xhb.androidx.XBanner;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import ui.activity.AddHousingActivity;
import ui.activity.AllBuildingActivity;
import ui.activity.BuildingDetailActivity;
import ui.activity.IntegralRuleActivity;
import ui.activity.MapDetailActivity;
import ui.adapter.AreaListAdapter;
import ui.adapter.HousesListAdapter;
import ui.adapter.NearFloorAdapter;
import ui.adapter.PriceFilterAdapter;

import static android.content.Context.WIFI_SERVICE;

/**
 * 房源
 * A simple {@link Fragment} subclass.
 * Use the {@link HouseResouceFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HouseResouceFragment extends BaseFragment<HouseSoucePresenter> implements HouseSouceView {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.smartRefresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.rl_area)
    RelativeLayout rlArea;
    @BindView(R.id.rl_price)
    RelativeLayout rlPrice;
    @BindView(R.id.rl_mianji)
    RelativeLayout rlMianji;
    @BindView(R.id.rl_more)
    RelativeLayout rlMore;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.xbanner)
    XBanner xbanner;
    @BindView(R.id.tv_count1)
    TextView tvCount1;
    @BindView(R.id.tv_count2)
    TextView tvCount2;
    @BindView(R.id.tv_count3)
    TextView tvCount3;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.recommend_recycle)
    RecyclerView recommendRecycle;
    @BindView(R.id.scrollView)
    CoordinatorLayout nestedScrollView;
    @BindView(R.id.ll_choose)
    LinearLayout llChoose;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.appbarLayout)
    AppBarLayout appBarLayout;

    @BindView(R.id.iv_map)
    ImageView ivMap;

    @BindView(R.id.iv_test)
    ImageView ivTest;
    private int page = 1;
    private int tag = 1;
    private int pageSize = 10;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public static int cityType = 1;
    private Observable<BaseData<NearHousingBean>> observable1;
    private Observable<BaseData<List<HomeBannerBean>>> observable2;
    private Observable<BaseData<HousingCountBean>> observable3;
    private NearFloorAdapter nearFloorAdapter;
    private Observable<BaseData<HousesListBean>> observable4;

    public HouseResouceFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static HouseResouceFragment newInstance(String param1, String param2) {
        HouseResouceFragment fragment = new HouseResouceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    String JsonData;
    List<CategoryBean> categoryList2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        JsonData = new GetJsonDataUtil().getJson(getActivity(), "menu.json");//获取assets目录下的json文件数据
        categoryList2 = new Gson().fromJson(JsonData, new TypeToken<List<CategoryBean>>() {
        }.getType());

    }


    @Override
    protected HouseSoucePresenter createPresenter() {
        return new HouseSoucePresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_huose_resouce;
    }

    HousesListAdapter housesListAdapter;
    TextWatcher textWatcher;
    private ShareHelper shareHelper = new ShareHelper(getActivity());
    @Override
    public void initView(View rootView) {
        super.initView(rootView);
        initParam();
        housesListAdapter = new HousesListAdapter(getActivity());
        recycleView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleView.addItemDecoration(new SpacesItemDecoration(16));
        recycleView.setAdapter(housesListAdapter);

        nearFloorAdapter = new NearFloorAdapter();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        recommendRecycle.setLayoutManager(linearLayoutManager);
        recommendRecycle.setAdapter(nearFloorAdapter);
        nearFloorAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<NearHousingBean.ListBean> listBeans = adapter.getData();
                Intent intent = new Intent(getActivity(), BuildingDetailActivity.class);
                intent.putExtra("housingid", listBeans.get(position).getFloorId());
                intent.putExtra("type", 1);
                ImageView imageView = view.findViewById(R.id.iv_logo);
                ActivityOptionsCompat options = ActivityOptionsCompat
                        .makeSceneTransitionAnimation(getActivity(),
                                imageView, "logo");
                startActivity(intent, options.toBundle());
            }
        });
        housesListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                List<HousesListBean.ListBean> data = adapter.getData();
                String url = ApiConstant.BASE_SERVER_URL + "shareHousing/getFloor?floorId="+data.get(position).getFloorId();
                if (view.getId() == R.id.share_wx) {
                    shareHelper.shareWx(data.get(position).getFloorImage(),url);
                } else if (view.getId() == R.id.share_pyq) {
                    shareHelper.shareWechatMoments(data.get(position).getFloorImage(), url);
                }
            }
        });
        shareHelper.setShareListener(new ShareHelper.onShareListener() {
            @Override
            public void shareSuccess() {
            }
        });
        if (textWatcher != null) {
            etSearch.removeTextChangedListener(textWatcher);
        }
        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                Log.e("搜索", s.toString());
                if (TextUtils.isEmpty(s.toString())) {
                    tvCancel.setBackgroundResource(R.mipmap.icon_search);
                    tvCancel.setText("");
                    tag = 1;
                    page = 1;
                    housesBean = new HousesBean();
                    housesBean.setPageNum(page);
                    housesBean.setPageSize(pageSize);
                    getHousingList();
                } else {
                    tvCancel.setBackgroundResource(0);
                    tvCancel.setText("取消");
                }
            }
        };
        etSearch.addTextChangedListener(textWatcher);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(etSearch.getText().toString().trim())) {
                        tag = 1;
                        housesBean = new HousesBean();
                        housesBean.setPageNum(page);
                        housesBean.setPageSize(pageSize);
                        housesBean.setFloorName(etSearch.getText().toString());
                        getHousingList();
                    }
                    return true;
                }
                return false;
            }
        });
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                tag = 1;
                housesBean = new HousesBean();
                housesBean.setPageNum(page);
                housesBean.setPageSize(pageSize);
                loadData();
            }
        });
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                tag = 2;
                housesBean = new HousesBean();
                housesBean.setPageNum(page);
                housesBean.setPageSize(pageSize);
                loadData();
            }
        });

        housesBean = new HousesBean();
        housesBean.setPageNum(page);
        housesBean.setPageSize(pageSize);

        housesListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<HousesListBean.ListBean> listBeans = adapter.getData();
                Intent intent = new Intent(getActivity(), BuildingDetailActivity.class);
                intent.putExtra("housingid", listBeans.get(position).getFloorId());
                intent.putExtra("type", 1);
                ImageView imageView = view.findViewById(R.id.iv_logo);
                ActivityOptionsCompat options = ActivityOptionsCompat
                        .makeSceneTransitionAnimation(getActivity(),
                                imageView, "logo");
                startActivity(intent, options.toBundle());
            }
        });
    }

    private HousesBean housesBean;
    NearBean nearBean = new NearBean();
    private String ip;

    public String getWifiMacAddress() {
        WifiManager wm = (WifiManager) Objects.requireNonNull(getActivity()).getApplicationContext().getSystemService(WIFI_SERVICE);
        if (wm != null) {
            WifiInfo winfo = wm.getConnectionInfo();
            return winfo.getBSSID();
        }
        return null;
    }
    @Override
    protected void loadData() {
      /*  new Thread(new Runnable() {
            @Override
            public void run() {
                ip = NetWorkUtils.GetNetIp();
            }
        }).start();
        String newMac = NetWorkUtils.getIpAddrMaskForInterfaces("eth0");
        boolean b = IpV4Util.ipIsValid( "36.24.122.78","125.122.37.230");

        int i = NetUtils.checkNetSegment("255.0.0.0", "192.168.0.69", NetWorkUtils.getLocalIpAddress());

        boolean inSameLAN = SameLAN.INSTANCE.isInSameLAN("192.168.0.113", "255.0.0.0", "192.168.0.75", "255.255.255.0");
        Log.e("IpV4Util", i+"  "+ NetWorkUtils.getLocalIpAddress()+"  "+newMac+" "+inSameLAN);*/
        //http://fuyinoss.oss-cn-hangzhou.aliyuncs.com/android/1609137614902.jpg

//        Log.e("WifiInfo", WifiConfig.getWifiMacAddress(getActivity())+"   "+WifiConfig.getWifiName(getActivity()));
        nearBean.setLatitude(String.valueOf(Contans.latitude));
        nearBean.setLongitude(String.valueOf(Contans.longitude));

        nearBean.setPageSize(8);
        observable1 = ApiRetrofit.getInstance().getApiService().floorNearbyListPage(nearBean);
        observable2 = ApiRetrofit.getInstance().getApiService().banner("index_banner");
        observable3 = ApiRetrofit.getInstance().getApiService().getHousingCount(0);
        observable4 = ApiRetrofit.getInstance().getApiService().getfloorList(housesBean);
        mPresenter.getBanner("");
       /* observable1.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<BaseData<NearHousingBean>>() {
                    @Override
                    public void call(BaseData<NearHousingBean> nearHousingBeanBaseData) {
                        if (null != nearHousingBeanBaseData.data) {
                            nearFloorAdapter.setNewData(nearHousingBeanBaseData.data.getList());
                        } else {
                            AppUtils.toLogin(getActivity());
                        }
                    }
                 }).observeOn(Schedulers.io())
                .flatMap(new Func1<BaseData<NearHousingBean>, Observable<BaseData<List<HomeBannerBean>>>>() {
                    @Override
                    public Observable<BaseData<List<HomeBannerBean>>> call(BaseData<NearHousingBean> nearHousingBeanBaseData) {
                        return observable2;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseData<List<HomeBannerBean>>>() {
                    @Override
                    public void call(BaseData<List<HomeBannerBean>> housesListBeanBaseData) {

                    }
                }
                );*/
        Observable.merge(observable4,observable1, /*observable2,*/ observable3)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BaseData baseData) {
                        if (null != baseData.errMessage && baseData.errMessage.equals(Contans.NET_ERROR_MSG)) {
                            AppUtils.toLogin(getActivity());
                            return;
                        }
                        Log.e("homeApi", new Gson().toJson(baseData));
                        if (baseData.data instanceof NearHousingBean) {
                            NearHousingBean nearHousingBean = (NearHousingBean) baseData.data;
                            if (null != nearHousingBean) {
                                nearFloorAdapter.setNewData(nearHousingBean.getList());
                            }
                        } else if(baseData.data instanceof  HousingCountBean){
                            HousingCountBean housingCountBean = (HousingCountBean) baseData.data;
                            tvCount1.setText(housingCountBean.getUpdateHousingTotal() + "");
                            tvCount2.setText(housingCountBean.getHousingTotal() + "");
                            tvCount3.setText(housingCountBean.getFloorTotal() + "");
                        }else {
                            smartRefresh.finishLoadMore();
                            smartRefresh.finishRefresh();
                            HousesListBean housesListBean = (HousesListBean) baseData.data;
                            if (housesListBean.getList().size() <= 0 || null == housesListBean) {
                                housesListAdapter.setEmptyView(R.layout.layout_nodata_search, recycleView);
                            }
                            if (tag == 1) {
                                housesListAdapter.setNewData(housesListBean.getList());
                            } else {
                                housesListAdapter.addData(housesListBean.getList());
                            }
                        }
                    }
                });
    }

    private void showBanner(List<HomeBannerBean> list) {
        List<String> imgList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            imgList.add(list.get(i).getValue());
        }
        xbanner.setData(imgList, null);
        xbanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                GlideUtils.loadRoundedCornersImage(imgList.get(position), (ImageView) view, 5);
            }
        });
        xbanner.setCustomPageTransformer(null);
        xbanner.setPageChangeDuration(500);
    }

    private void getHousingList() {
        mPresenter.getHouseList(housesBean);

    }

    @OnClick({R.id.iv_map,R.id.tv_more,R.id.tv_cancel, R.id.et_search, R.id.tv_add, R.id.rl_area, R.id.rl_price, R.id.rl_mianji, R.id.rl_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_map:
                showDetailMap();
                break;
            case R.id.tv_more:
                startActivity(new Intent(getActivity(), AllBuildingActivity.class));
                break;
            case R.id.tv_cancel:
                if (tvCancel.getText().equals("取消")) {
                    etSearch.setText("");
                    AppUtils.hideInput(etSearch);
                }
                break;
            case R.id.et_search:
                break;
            case R.id.tv_add:
                Intent intent = new Intent(getActivity(), AddHousingActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.rl_area:
                showAreaData();
                break;
            case R.id.rl_price:

                showPriceFilterDialog();
                break;
            case R.id.rl_mianji:
                showMianJiFilterDialog();
                break;
            case R.id.rl_more:
                showOtherFilterDialog();
                break;
            default:
        }
    }

    private void showDetailMap() {
        Intent intent = new Intent(getActivity(), MapDetailActivity.class);
        intent.putExtra("type", 1);
        startActivity(intent);
    }

    private void showMianJiFilterDialog() {
        scrollToTop();
        AreaFilterPopwindow areaFilterPopwindow = new AreaFilterPopwindow(getActivity());
        areaFilterPopwindow.setSelectPo(areaSelect);
        areaFilterPopwindow.showPop(rlArea);
        PriceFilterAdapter priceFilterAdapter = areaFilterPopwindow.getPriceFilterAdapter();
        priceFilterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                areaFilterPopwindow.onDismiss();
                areaSelect = position;
                tag = 1;
                page = 1;
                List<PriceFilterBean> data = adapter.getData();
                housesBean = new HousesBean();
                housesBean.setPageNum(page);
                housesBean.setPageSize(pageSize);
                housesBean.setHousingArea(data.get(position).getId());
                getHousingList();
            }
        });

    }

    private int priceSelect = -1;
    private int areaSelect = -1;

    private void showPriceFilterDialog() {
        scrollToTop();
        PriceFilterPopwindow priceFilterPopwindow = new PriceFilterPopwindow(getActivity());
        priceFilterPopwindow.setSelectPo(priceSelect);
        priceFilterPopwindow.showPop(rlArea);
        PriceFilterAdapter priceFilterAdapter = priceFilterPopwindow.getPriceFilterAdapter();
        priceFilterAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                priceFilterPopwindow.onDismiss();
                tag = 1;
                page = 1;
                priceSelect = position;
                List<PriceFilterBean> data = adapter.getData();
                housesBean = new HousesBean();
                housesBean.setPageNum(page);
                housesBean.setPageSize(pageSize);
                housesBean.setRentPrice(data.get(position).getId());
                getHousingList();
            }
        });
    }

    Integer isBigYeZhu = null;
    Integer isGoodHouse = null;
//    Integer houseStatus = 1;
    private List<FiltrateBean> dictList = new ArrayList<>();

    private void showOtherFilterDialog() {
        scrollToTop();
        isBigYeZhu = null;
        isGoodHouse = null;
//        houseStatus = 1;
        FlowPopWindow flowPopWindow = new FlowPopWindow(getActivity(), dictList);
        flowPopWindow.showAsDropDown(rlArea, 0, -10);
        flowPopWindow.setOnConfirmClickListener(new FlowPopWindow.OnConfirmClickListener() {
            @Override
            public void onConfirmClick() {
                StringBuilder sb = new StringBuilder();
                for (FiltrateBean fb : dictList) {
                    List<FiltrateBean.Children> cdList = fb.getChildren();
                    for (int x = 0; x < cdList.size(); x++) {
                        FiltrateBean.Children children = cdList.get(x);
                        if (children.isSelected()) {
                            sb.append(fb.getTypeId() + "" + children.getId());
                        }
                    }
                }
                int index;
                for (index = 2; index < sb.length(); index += 3) {
                    sb.insert(index, ',');
                }
                String[] array = sb.toString().split(",");
                if (array.length <= 0) {
                    return;
                }
                for (int i = 0; i < array.length; i++) {
                    if (!TextUtils.isEmpty(array[i])) {
                        if (array[i].startsWith("A")) { //第一个筛选
                            isBigYeZhu = Integer.parseInt(array[i].substring(array[i].length() - 1, array[i].length()));
                        } else if (array[i].startsWith("B")) {
                            isGoodHouse = Integer.parseInt(array[i].substring(array[i].length() - 1, array[i].length()));
                        } else if (array[i].startsWith("C")) {
//                            houseStatus = Integer.parseInt(array[i].substring(array[i].length() - 1, array[i].length()));
                        }
                    }
                }

                tag = 1;
                page = 1;
                housesBean = new HousesBean();
                housesBean.setPageNum(page);
                housesBean.setPageSize(pageSize);
                housesBean.setQualityHouse(isGoodHouse);
                housesBean.setBigOwner(isBigYeZhu);
                getHousingList();
            }
        });
    }

    private void initParam() {
        String[] sexs = {"是", "否"}; //0否 1是
        Integer[] idS = {1, 0};
        String[] colors = {"是", "否"};

        FiltrateBean fb1 = new FiltrateBean();
        fb1.setTypeName("是否大业主");
        fb1.setTypeId("A");
        List<FiltrateBean.Children> childrenList = new ArrayList<>();
        for (int x = 0; x < sexs.length; x++) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(sexs[x]);
            cd.setId(idS[x]);
            childrenList.add(cd);
        }
        fb1.setChildren(childrenList);

        FiltrateBean fb2 = new FiltrateBean();
        fb2.setTypeName("是否优质房源");
        fb2.setTypeId("B");
        List<FiltrateBean.Children> childrenList2 = new ArrayList<>();
        for (int x = 0; x < colors.length; x++) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(colors[x]);
            cd.setId(idS[x]);
            childrenList2.add(cd);
        }
        fb2.setChildren(childrenList2);


        dictList.add(fb1);
        dictList.add(fb2);
//        dictList.add(fb3);
    }

    Integer flag = 1;
    private int areaType;
    RecyclerView recyclerView1;
    RecyclerView recyclerView2;
    RecyclerView recyclerView3;

    AreaListAdapter areaListAdapter1;
    AreaListAdapter areaListAdapter2;
    AreaListAdapter areaListAdapter3;

    //	1：市 -区-地点 2：楼盘 3：栋座
    private Integer parentId = 16;

    public void scrollToTop() {
        //拿到 appbar 的 behavior,让 appbar 滚动
        ViewGroup.LayoutParams layoutParams = appBarLayout.getLayoutParams();
        CoordinatorLayout.Behavior behavior =
                ((CoordinatorLayout.LayoutParams) layoutParams).getBehavior();
        if (behavior instanceof AppBarLayout.Behavior) {
            AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
            //拿到下方tabs的y坐标，即为我要的偏移量
            float y = recommendRecycle.getY() + recommendRecycle.getHeight();
            //注意传递负值
            appBarLayoutBehavior.setTopAndBottomOffset((int) -y);
        }
    }

    private Integer areaId;
    private void showAreaData() {
        scrollToTop();
        flag = 1;
        parentId = 16;
        CityDetailFilterPopwindow areaFilterPopwindow = new CityDetailFilterPopwindow(getActivity());
        areaFilterPopwindow.showPop(rlArea);
        recyclerView1 = areaFilterPopwindow.getCurrentView(1);
        recyclerView2 = areaFilterPopwindow.getCurrentView(2);
        recyclerView3 = areaFilterPopwindow.getCurrentView(3);

        areaListAdapter1 = new AreaListAdapter();
        areaListAdapter2 = new AreaListAdapter();
        areaListAdapter3 = new AreaListAdapter();

        recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView2.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView3.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView1.setAdapter(areaListAdapter1);
        recyclerView2.setAdapter(areaListAdapter2);
        recyclerView3.setAdapter(areaListAdapter3);
        areaListAdapter3.setSelect(-1);
        areaListAdapter2.setSelect(-1);

        List<AreaListBean> list1 = new ArrayList<>();
        list1.add(new AreaListBean(16, "区域", "区域"));
        list1.add(new AreaListBean(2, "地铁", "地铁"));
        areaListAdapter1.setNewData(list1);
        recyclerView1.post(new Runnable() {
            @Override
            public void run() {
                View viewByPosition = recyclerView1.getLayoutManager().findViewByPosition(0);
                viewByPosition.performClick();
            }
        });
        getAreaData(flag, 16);
        areaListAdapter1.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                flag = 1;
                areaType = 1;
                areaListAdapter1.setSelect(position);
                if (position == 0) {//城市
                    cityType = 1;
                    getAreaData(flag, 16);
                } else { //地铁
                    cityType = 2;
//                    areaListAdapter1.setNewData(list1);
                    getSubwayData(flag, 0);
                }
            }
        });

        areaListAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                areaListAdapter2.setSelect(position);
                flag = 1;
                areaType = 2;
                AreaListBean areaListBean = (AreaListBean) adapter.getData().get(position);
                parentId = areaListBean.getId();
                if (cityType == 1) {
                    getAreaData(flag, parentId);
                } else {
                    getSubwayData(flag, parentId);
                }
            }
        });

        areaListAdapter3.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                areaListAdapter3.setSelect(position);
                flag = 2;
                areaType = 3;
                AreaListBean areaListBean = (AreaListBean) adapter.getData().get(position);
                parentId = areaListBean.getId();

                housesBean.setAreaId(areaListBean.getAreaId());
                areaId = areaListBean.getId();
                if (cityType == 1) {
                    getAreaData(flag, parentId);
                } else {
                    getSubwayData(flag, parentId);
                }
            }
        });

        TextView tvSure = (TextView) areaFilterPopwindow.getView(R.id.tv_suer);
        areaFilterPopwindow.getView(R.id.tv_default).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                areaFilterPopwindow.getPopWindow().dissmiss();
                housesBean = new HousesBean();
                housesBean.setPageNum(page);
                housesBean.setPageSize(pageSize);
                getHousingList();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                if (cityType == 1) {
                    housesBean = new HousesBean();
                    housesBean.setPageNum(page);
                    housesBean.setPageSize(pageSize);
                    housesBean.setPlaceId(areaListAdapter3.getSelectId());
                    housesBean.setAreaId(areaId);
                } else {
                    housesBean = new HousesBean();
                    housesBean.setPageNum(page);
                    housesBean.setPageSize(pageSize);
                    housesBean.setSubwayId(areaListAdapter3.getSelectId());
                    housesBean.setSubwayParentId(areaListAdapter2.getSelectId());
                }
                getHousingList();
                areaFilterPopwindow.getPopWindow().dissmiss();
                //areaId buildingId floorId floorId
            }
        });
    }

    private void getAreaData(Integer flag, Integer parentID) {
        mPresenter.getAreaList(flag, parentID);
    }

    public void getSubwayData(int flag, int parentID) {
        mPresenter.getSubwayData(parentID);
    }

    @Override
    public void getHouseSuccess(HousesListBean housesListBean) {
        Log.e("楼盘", new Gson().toJson(housesListBean));
        smartRefresh.finishLoadMore();
        smartRefresh.finishRefresh();
        if (housesListBean.getList().size() <= 0 || null == housesListBean) {
            housesListAdapter.setEmptyView(R.layout.layout_nodata_search, recycleView);
        }
        if (tag == 1) {
            housesListAdapter.setNewData(housesListBean.getList());
        } else {
            housesListAdapter.addData(housesListBean.getList());
        }
    }

    private List<AreaListBean> areaListBeans;

    @Override
    public void getAreaListSuccess(List<AreaListBean> listBeans) {
        areaListBeans = listBeans;
        if (areaType == 1) {
//            areaListBeans.add(0,new AreaListBean(null,"全部","全部"));
            areaListAdapter2.setNewData(areaListBeans);
            if (areaListBeans.size() <= 0) {
//                areaListAdapter2.se
            }
            recyclerView2.post(new Runnable() {
                @Override
                public void run() {
//                    recyclerView2.getLayoutManager().findViewByPosition(0).performClick();
                }
            });
        } else if (areaType == 2) {
            areaListAdapter3.setNewData(areaListBeans);
        }
    }

    @Override
    public void getSubwatdataSuccess(List<AreaListBean> listBeans) {
        areaListBeans = listBeans;
        if (areaType == 1) {
            areaListAdapter2.setNewData(areaListBeans);
            if (areaListBeans.size() <= 0) {
//                areaListAdapter2.se
            }
            recyclerView2.getLayoutManager().findViewByPosition(0).performClick();
        } else if (areaType == 2) {
            areaListAdapter3.setNewData(areaListBeans);
            recyclerView3.getLayoutManager().findViewByPosition(0).performClick();
        } else if (areaType == 3) {
        }
    }

    @Override
    public void onError() {

    }

    @Override
    public void getMatchHousingSuccess(HousesListBean housesListBean) {

    }

    @Override
    public void collectHousingSuccess(BaseData baseData, int i) {

    }

    @Override
    public void removecollectHousingSuccess(BaseData baseData, int i) {

    }

    @Override
    public void getFloorCountSuccess(HousingCountBean housingCountBean) {
        tvCount1.setText(housingCountBean.getUpdateHousingTotal() + "");
        tvCount2.setText(housingCountBean.getHousingTotal() + "");
        tvCount3.setText(housingCountBean.getFloorTotal() + "");
    }

    @Override
    public void getBannerSuccess(List<HomeBannerBean> homeBannerBeans) {
        List<String> imgList = new ArrayList<>();
        for (int i = 0; i < homeBannerBeans.size(); i++) {
            imgList.add(homeBannerBeans.get(i).getValue());
        }
        xbanner.setData(imgList, null);
        xbanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                GlideUtils.loadRoundedCornersImage(imgList.get(position), (ImageView) view, 5);
            }
        });
        xbanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {
                if (position == 1) {
                    startActivity(new Intent(getActivity(), IntegralRuleActivity.class));
                }
            }
        });
        xbanner.setCustomPageTransformer(null);
        xbanner.setPageChangeDuration(500);
    }
}